package org.jeecg.modules.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.boot.starter.rabbitmq.core.BaseRabbiMqHandler;
import org.jeecg.boot.starter.rabbitmq.listenter.MqListener;
import org.jeecg.common.annotation.RabbitComponent;
import org.jeecg.common.base.BaseMap;
import org.jeecg.common.constant.RedisCacheConstant;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.manage.service.IMCaishuiTaskSettleService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;

import javax.annotation.Resource;

/**
 * 【批次与明细查询】处理RabbitMq接受者
 *
 * 定义接收者（可以定义N个接受者，消息会均匀的发送到N个接收者中）
 *
 * （@RabbitListener声明类上，一个类只能监听一个队列）
 * @author: yfkj
 * @date: 2023/03/21
 */
@Slf4j
@RabbitListener(queues = "caisui_batch_and_detail_queue")
@RabbitComponent(value = "BatchAndDetailReceiver")
public class BatchAndDetailReceiver extends BaseRabbiMqHandler<BaseMap> {

    @Resource
    private IMCaishuiTaskSettleService iMCaishuiTaskSettleService;
    @Autowired
    private RedisUtil redisUtil;

    @RabbitHandler
    public void onMessage(BaseMap baseMap, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        super.onMessage(baseMap, deliveryTag, channel, new MqListener<BaseMap>() {
            @Override
            public void handler(BaseMap map, Channel channel) {
                //业务处理
                String orderNo = oConvertUtils.getString(map.get("orderNo"));
                if(oConvertUtils.isEmpty(orderNo)){
                    log.error("【批次与明细查询】异步处理RabbitMq接受数据错误!");
                    return;
                }

                try {
                    Object isRepeat = redisUtil.get(RedisCacheConstant.YSW_BATCH_AND_DETAIL_REPEAT_CACHE + ":" + orderNo);
                    if("1".equals(isRepeat.toString())){
                        //批次与明细查询
                        iMCaishuiTaskSettleService.handleTaskSettle(orderNo);
                    }else {
                        log.error("【批次与明细查询】异步处理请求重复!");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    redisUtil.del(RedisCacheConstant.YSW_BATCH_AND_DETAIL_REPEAT_CACHE + ":" + orderNo);
                }
            }
        });
    }

}